<?php

namespace app\index\util;

use think\Cache;
use think\Config;
use think\Loader;

class Taoke
{
    public function __construct()
    {
        Loader::import('@.util.tbk.TopSdk');
    }

    public static function get_instance($name)
    {
        $client = new \TopClient;
        $client->appkey = Config::get('utao.appkey');
        $client->secretKey = Config::get('utao.secretkey');
        $client->format = 'json';
        $class = '\\' . $name;
        $api = new $class;
        return [$client, $api];
    }

    /**
     * 优惠券搜索
     * @param $data
     * @return mixed
     */
    public function search_coupon($data)
    {
        $cache_name = serialize([$data]);// 缓存名 用于唯一性碰撞
        if ($cache = Cache::get($cache_name)) {
            return $cache;
        }
        list($client, $api) = self::get_instance('TbkDgMaterialOptionalRequest');
        if (Config::get('utao.adzone_id')) {
            $api->setAdzoneId(Config::get('utao.adzone_id'));
        }
        // 兼容参数配置
        if (!is_array($data)) {
            $api->setQ($data);
        } else {
            foreach ($data as $k => $v) {
                // 转换驼峰命名
                $col = Loader::parseName($k, 1);
                if ($col) {
                    $api->{'set' . $col}($v);
                }
            }
        }
        $res = $client->execute($api);
        // 将返回结果转换成数组
        $res = json_decode(json_encode($res), true);
        if (isset($res['result_list'])) {
            foreach ($res['result_list']['map_data'] as $key => &$row) {
                // 虽然限制了只搜有优惠券的数据 但是淘宝接口仍然会抛出小部分没有优惠券的数据
                // 检测是否有优惠券
                if ($row['coupon_remain_count'] <= 0) {
                    unset($res['result_list']['map_data'][$key]);
                    continue;// 没有则进入下一个循环
                }
                $coupon_start_fee = (float)@$row['coupon_start_fee'];// 优惠券满减价
                $row['coupon_price'] = $zk_final_price = (float)$row['zk_final_price']; // 商品售价
                $coupon_amount = (float)@$row['coupon_amount']; // 优惠券面额
                if (($coupon_start_fee > 0 && $zk_final_price >= $coupon_start_fee) || $coupon_start_fee <= 0) {
                    $row['coupon_price'] = $zk_final_price - $coupon_amount;// 券后价
                }
                // 淘宝接口抛出的数据类型不一  需要转换成同一类型 否则php会抛出警告
                if (isset($row['small_images']) &&
                    $row['small_images'] &&
                    isset($row['small_images']['string'])) {
                    if (is_string($row['small_images']['string'])) {
                        $row['small_images']['string'] = [$row['small_images']['string']];
                    }
                } else {
                    $row['small_images']['string'] = [];
                }
                // 只加https
                isset($res['coupon_share_url']) && $row['coupon_share_url'] = $this->push_https($row['coupon_share_url']);
                isset($row['url']) && $row['url'] = $this->push_https($row['url']);
                // 解决警告
                !$row['short_title'] && $row['short_title'] = $row['title'];
            }
//            Cache::set($cache_name, $res, 3600); // 自动缓存一个小时
        }
        return $res;
    }

    /**
     * 自动追加https头
     * @param $url
     * @return string
     */
    protected function push_https($url)
    {
        if (stripos($url, 'https://') !== 0) {
            $url = 'https://' . preg_replace('!^//!s', '', $url);
        }
        return $url;
    }

    public function parse_data(&$data)
    {
        if (!isset($data->result_list)) {
            return false;
        }
        $list = &$data->result_list->map_data;
        foreach ($list as $k => $row) {
            foreach ($row as $kk => $v) {
                if (empty($v)) {
                    $v = '';
                    $list[$k][$kk] = null;
                }
            }
        }
    }

    /**
     * url生成淘口令
     * @param $text
     * @param $url
     * @param $logo
     * @return bool
     */
    public function tpwd($text, $url, $logo)
    {
        list($client, $api) = self::get_instance('TbkTpwdCreateRequest');
        $api->setText($text);
        $api->setUrl($url);
        $api->setLogo($logo);
        $res = $client->execute($api);
        if (!$res || $res->error_response)
            return false;
        return $res->data->model;
    }
}